package com.ruike.alisurface.mqtt;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import com.ruike.alisurface.Constant;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.Serials.ShopInfoUtils;
import com.ruike.alisurface.services.AppRunMonitoringService;
import com.ruike.alisurface.utils.DeviceUtils;
import com.ruike.alisurface.utils.ThreadUtils;
import com.voodoo.lib_frame.Config;
import com.voodoo.lib_utils.GsonUtils;
import com.voodoo.lib_utils.L;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import static com.ruike.alisurface.Constant.Mqtt.passWord;
import static com.ruike.alisurface.Constant.Mqtt.userName;

/**
 * Author: voodoo
 * CreateDate: 2020-03-27 027 上午 10:48
 * Description: Mqtt 服务，本类尽量不要修改，订阅消息和回传消息处理
 * 的操作都在{@link MqttOperation}中
 */
public class MQTTService extends Service {

    public static MqttAndroidClient mqttClient;//mqtt 客户端对象
    public MqttConnectOptions mqttConnectOptions;//mqtt 客户端配置信息

    private static Timer timer;//倒计时
    boolean isMQTTflag;//mqtt是否在线

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    MqttOperation mqttOperation;//mqtt处理对象
    private Timer runtimer;// 服务互相拉起计时
    private TimerTask runtimerTask;// 服务计时

    /**
     * 检测AppRunMonitoring 服务是否运行
     */
    public void chickServicr() {
        runtimer = new Timer();
        runtimerTask = new TimerTask() {
            @Override
            public void run() {
                if (!ServiceUtils.isServiceRunning(MQTTService.this, AppRunMonitoringService.class.getName())) {
                    L.e(" 检测到AppRunMonitoringService  未启动   开始启动");
                    ServiceUtils.startService(MQTTService.this, AppRunMonitoringService.class);
                }
            }
        };
        runtimer.schedule(runtimerTask, 500, 60_000);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        chickServicr();
        L.i("mqtt-onCreate--   mqtt 的创建和后续配置");
        ThreadUtils.post(new Runnable() {
            @Override
            public void run() {
                initMqtt();
                mqttOperation = new MqttOperation(MQTTService.this);
                mqttOperation.getHandle();
                mqttOperation.ConnectMqtt(mqttConnectOptions, new MyMqttActionListener());
            }
        });
    }

    int i = 0;//第一次连接成功后 启动温控信息查询

    public void sendIccidInfo() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                String sn = DeviceUtils.getDeviceSn();
                String iccid = DeviceUtils.getSimSerialNumber();
                HashMap<String, String> coflist = ShopInfoUtils.BzVersion();
                coflist.put("iccid", iccid + "");
                coflist.put("sn", sn);
                String data = GsonUtils.MapToJson(coflist);
                L.i("mqtt-发送sn 及iccid--" + data);

                if (mqttOperation != null) {
                    mqttOperation.handler.sendEmptyMessage(0x02);
                    MqttOperation.publishMessage("rkt/mch/savesim/", data);
                }
            }
        }, 20000);
    }

    /**
     * 初始化mqtt 配置及连接
     */
    public void initMqtt() {
        L.i(" 初始化mqtt 配置 ");
        mqttClient = new MqttAndroidClient(getApplicationContext(), Constant.Mqtt.BASE_URL,
                Constant.Mqtt.CLIENT_ID);

        mqttClient.setCallback(new MyMqttCallbackExtended()); // 设置MQTT监听并且接受消息
        mqttConnectOptions = new MqttConnectOptions(); // 设置MQTT 配置类
        mqttConnectOptions.setConnectionTimeout(Config.MQTT_TIME_OUT); // 连接超时 单位：秒
        mqttConnectOptions.setKeepAliveInterval(Config.MQTT_HEARTBEAT_TIME); // 心跳包发送间隔，单位：秒
//        mqttConnectOptions.setAutomaticReconnect(true); // 开启自动重连
        mqttConnectOptions.setCleanSession(true); // 客户端和服务器是否记录重启和重连的状态。

        try {
            // Signature 方式 参考 https://help.aliyun.com/document_detail/54225.html
//            mqttConnectOptions.setUserName("Signature|" + Constant.Mqtt.ACCESS_KEY + "|" + Constant.Mqtt.INSTANCE_ID);
//            mqttConnectOptions.setPassword(AliTool.macSignature(Constant.Mqtt.CLIENT_ID, Constant.Mqtt.SECRET_KEY).toCharArray());
            mqttConnectOptions.setUserName(userName);
            mqttConnectOptions.setPassword(passWord.toCharArray());
            mqttConnectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
        } catch (Exception e) {
            L.e("Mqtt Set UserName Or Password Error", e.toString());
        }
//        doClientConnection(); // 去做链接
    }

    /**
     * 连接MQTT服务器
     */
    public void doClientConnection() {
        L.i("开始链接Mqtt服务器   是否在线1=" + mqttClient.isConnected());
        if (!mqttClient.isConnected()) {
            try {
                L.i("开始链接Mqtt服务器   是否在线2=" + mqttClient.isConnected());
                mqttClient.connect(mqttConnectOptions, null, new MyMqttActionListener());
            } catch (MqttException e) {
                L.e("链接Mqtt服务器异常", e.toString());
                e.printStackTrace();
            }
        }
    }


    /**
     * Mqtt 连接的回调
     */
    public class MyMqttActionListener implements IMqttActionListener {

        @Override
        public void onSuccess(IMqttToken asyncActionToken) {
            L.i("Mqtt 连接成功...");
//            DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
//            disconnectedBufferOptions.setBufferEnabled(true); // 设置启用缓冲区
//            disconnectedBufferOptions.setBufferSize(100); // 设置缓冲区大小
//            disconnectedBufferOptions.setPersistBuffer(false); // 设置持久缓冲区
//            disconnectedBufferOptions.setDeleteOldestMessages(false); // 设置删除最早的消息
//            mqttClient.setBufferOpts(disconnectedBufferOptions);
            isMQTTflag = true;
            if (i++ == 0) {
                L.i("Mqtt 连接成功..发送iccid 及启动温控.");
                sendIccidInfo();
            }

            try {
                if (mqttOperation != null) {
                    mqttOperation.subscribeToTopic(mqttClient);
                }
            } catch (MqttException e) {
                L.e("设置订阅异常：" + e.toString());
            }
        }

        @Override
        public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
            L.i("Mqtt 连接失败...", asyncActionToken,
                    exception);
        }

    }

    /**
     * Mqtt 客户端连接后数据响应的回调及处理重连后的逻辑
     */
    public class MyMqttCallbackExtended implements MqttCallbackExtended {

        @Override
        public void connectComplete(boolean reconnect, String serverURI) {
            L.i("与服务器的连接成功完成...");

        }

        @Override
        public void connectionLost(Throwable exception) {
            L.i("Mqtt 与服务器的连接丢失...",
                    exception);
        }

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            String body = new String(message.getPayload());
            L.i("收到服务器消息", "中主题的名称：" + topic, "接收消息：" + body);
            ThreadUtils.post(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (mqttOperation != null) {
                            mqttOperation.processMsg(topic, body); // 处理回传的消息
                        }
                    } catch (JSONException e) {

                        L.i("mqtt--JSONException", e);
                        e.printStackTrace();
                    }
                }
            });

        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {

        }
    }

    // 当一个Message Event提交的时候这个方法会被调用
    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onMessageEvent(MsgEventBus event) {
        if (mqttOperation != null) {
            mqttOperation.doSerialPortData(event.getType(), event.getMessage());
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return Service.START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        L.i("mqtt-onDestroy-断开mqtt连接");
        //断开mqtt连接
        try {
            if (mqttClient != null && mqttClient.isConnected()) {
                mqttClient.disconnect();
                mqttClient.unregisterResources();
                mqttClient = null;
                mqttOperation = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (timer != null) {
            timer.cancel();
            timer.purge();
            timer = null;
        }
        i = 0;
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        stopSelf();
    }
}
